package cn.tedu;

import java.sql.*;
import java.util.Scanner;

/**
 * @Classname: Demo10
 * @Author: bromide
 * @CreateTime: 2022/5/10--10:57
 * @Version: V1.0
 * @Description:
 */
public class Demo10 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名:");
        String username = scanner.nextLine();
        System.out.print("请输入密码:");
        String password = scanner.nextLine();
        try(Connection conn = DBUtils.getConn()) {
//            Statement s = conn.createStatement();
            //select count(*) from user where username='' and password=''
            //select password from user where username='';select 1 from user
//            ResultSet set = s.executeQuery("select count(*) from user where username='"+username+"' and password='"+password+"'");

            //通过PreparedStatement解决SQL注入问题
            String sql = "select count(*) from user where username=? and password=?";
            /*
                编译SQL语句的时间点从之前执行时,提前到了创建对象时,好处是此时编译用户输入的内容,
                还不再SQL语句里面,只是将原有SQL语句进行编译,此时可以将原有SQL语句的逻辑部分锁死
             */
            PreparedStatement ps = conn.prepareStatement(sql);
            /*
                把?替换成变量1和2代表的是?的位置  此时替换时只能以值的形式添加到原有的SQL语句中,因为
                逻辑部分已经编译好 已经锁死,这样用户输入的内容则不会影响原有SQL语句的逻辑.
             */
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet set = ps.executeQuery();
            set.next();
            int count = set.getInt(1);
            if (count>0){
                System.out.println("验证成功!");
            }else {
                System.out.println("用户名或密码错误!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
